package com.bbs.service.impl;

import com.bbs.dao.CommentDao;
import com.bbs.dao.PostDao;
import com.bbs.dao.ReplyDao;
import com.bbs.entity.Comment;
import com.bbs.entity.Reply;
import com.bbs.service.ReplyService;
import com.bbs.utils.MyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.Date;
import java.util.List;
@Service("replyService")
public class ReplyServiceImpl implements ReplyService {
    @Autowired
    private ReplyDao replyDao;
    @Autowired
    private PostDao postDao;
    @Autowired
    private DataSourceTransactionManager transactionManager;
    @Autowired
    private CommentDao commentDao;

    @Override
    @Transactional
    public List<Reply> listReply(int pid){
        List<Reply> replyList = replyDao.listReply(pid);
        for (Reply reply : replyList){
//            列出每条回复下的评论
            List<Comment> commentList = replyDao.ListComment(reply.getId());
            reply.setCommentList(commentList);
        }
        return replyList;
    }


//    评论/回帖
@Override
    public int insert(Reply reply) {
        int flag = replyDao.insert(reply);//保存评论
        postDao.updateReplyCount(reply.getPid());//显示评论数
        return flag;
    }


//public int insert(Reply reply) {
//    TransactionStatus transactionStatus = transactionManager.getTransaction(new DefaultTransactionDefinition());
//    int flag = 0;//保存评论
//    try{
//        postDao.updateReplyCount(reply.getPid());//显示评论数
//        transactionManager.commit(transactionStatus);
//    }catch (Exception e){
//        flag = 0;
//        e.printStackTrace();
//        transactionManager.rollback(transactionStatus);
//    }
//    return flag;
//}

@Transactional
    public int reply(Reply reply){
        replyDao.insert(reply);//保存评论信息
//        int a = 1/0;//手动抛出异常
        postDao.updateReplyCount(reply.getPid());
        return 1;
}


    /**
     * 楼中楼评论回复
     * @param pid
     * @param sessionUid
     * @param rid
     * @param content
     */
    @Transactional
    @Override
    public void comment(int pid,int sessionUid,int rid,String content){
        Comment comment = new Comment();
        comment.setRid(rid);
        comment.setUid(sessionUid);
        comment.setCommentTime(MyUtil.formatDate(new Date()));
        comment.setContent(content);
        commentDao.insertComment(comment);
        //        todo 更新最后回帖的时间==>post reply_time
    }

}
